import os

from Config import *
from OutputProperty import OutputProperty
from CategoryHandler import CategoryHandler

class Parser:
    def __init__(self, owner):
        self.__billOwner = owner
        self.__inputProperties = []
        self.__outputProperties = []
        self.__categoryHandler = CategoryHandler()

    @property
    def BillOwner(self):
        return self.__billOwner

    @property
    def InputProperties(self):
        return self.__inputProperties

    @property
    def OutputProperties(self):
        return self.__outputProperties

    @property
    def CategoryPairs(self):
        return self.__categoryHandler.CategoryPairs

    def Parse(self, inputDir, outputPath):
        for d in os.listdir(inputDir):
            self._preSingleParse()
            self.__singleParse(os.path.join(inputDir, d))            
            self._postSingleParse()
        self._filterOutputs()
        if len(self.OutputProperties) <= 0:
            return
        with open(outputPath, "a", encoding = ENCODING) as f:
            for output in self.OutputProperties:
                outputs = [OutputProperty.ToString(i) for i in output]
                f.write(SEPARATOR.join(outputs) + "\n")
        
    def __singleParse(self, inputPath):
        with open(inputPath, encoding = ENCODING) as f:
            for l in f.readlines():
                line = l.strip()
                if line == "":
                    continue
                self._doParse(line)

    def _stringToCategory(self, str):
        for c in Category:
            if c.name == str:
                return c
        return Category.Other

    def _doParse(self, line):
        pass

    def _preSingleParse(self):
        self.__inputProperties = []

    def _postSingleParse(self):
        self._generateOutputs()

    def _generateOutputs(self):
        pass

    def _filterOutputs(self):
        pass

    def _getOutputCategory(self, items):
        matchNote = ["", 0]
        for note in self.CategoryPairs:
            index = 0
            match = False
            for i in note.split(INNER_SEPARATOR):
                if items[index] == i:
                    match = True
                    index += 1
                else:
                    match = False
                    break
            if match and index > matchNote[1]:
                matchNote = [note, index]
                if index == len(items):
                    break
        return (self.CategoryPairs[matchNote[0]], True) if matchNote[1] > 0 else (Category.Other, False)

